//
//  NSAFNetwork.m
//  JSToNativeDemo
//
//  Created by mouxiaochun on 15/7/7.
//  Copyright (c) 2015年 mouxiaochun. All rights reserved.
//ddddddd
//ew

#import "AIAFNetwork.h"
#import "AFNetworking.h"
#import "AIResultParser.h"


@implementation AIRequest (Network)

- (void) request {
  DebugLog(@"URL-->%@\n Param --> %@",self.requestURL,self.requestParams);
/*
  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  //设置网络请求超时时间
  [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
  manager.requestSerializer.timeoutInterval = 30.0f;//30.0f
  [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
  [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;" forHTTPHeaderField:@"Content-Type"];
  [self addHeaderParams:manager];
  manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",nil];
  [manager POST:self.requestURL
     parameters:self.requestParams
        success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
           (@"success-POST:%@",responseObject);
          [self  handleResponse:responseObject
                   responseData:operation.responseData] ;
        }
   
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          DebugLog(@"failurePOST:%@",error.description);
         
          [self  handleResponse:error
                   responseData:operation.responseData];
          
          
        }];
 */
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.0f;//30.0f
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;" forHTTPHeaderField:@"Content-Type"];
    [self addHeaderParams:manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",nil];

    [manager POST:self.requestURL parameters:self.requestParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
    NSLog(@"success-POST:%@",responseObject);
   
//    [self  handleResponse:responseObject
//             responseData:operation.responseData] ;
            [self  handleResponse:responseObject
                     responseData:nil] ;

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
    [self  handleResponse:error
             responseData:nil];

}];
   
  
}


- (void)uploadFile {
    
    //url地址
    
    NSString *url = self.requestURL; //[NSString stringWithFormat:@"%@%@/%@",BASED_URL,request.moduleName,request.functionName];
  /*
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",nil];
    [self addHeaderParams:manager];
//    NSString *_token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
//    [manager.requestSerializer  setValue:_token forHTTPHeaderField:@"token"];
    [self addHeaderParams:manager];
    AFHTTPRequestOperation *_operation = [manager POST:url
                                            parameters:nil
                             constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                 NSArray *keys = self.requestParams.allKeys;
                                 NSArray *values = self.requestParams.allValues;
                                 
                                 for (NSInteger i = 0; i < keys.count; i++) {
                                     NSString *key  = keys[i];
                                     NSString *value = [NSString stringWithFormat:@"%@",values[i]];
                                     if ([key isEqual:@"file"]) {
                                         NSString *path = [self.requestParams objectForKey:@"file"];
                                         NSError *error;
                                         [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file"  error:&error];
                                     }else {
                                         NSData *jsonData = [value dataUsingEncoding:NSUTF8StringEncoding];
                                         [formData appendPartWithFormData:jsonData name:key];
                                     }
                                     
                                 }
                                 
                             } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                 DebugLog(@"上传文件成功:%@",responseObject);
                                 [self  handleResponse:responseObject
                                          responseData:operation.responseData] ;
                                 
                             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                 DebugLog(@"上传文件失败:%@",error.description);
                                 
                                 [self  handleResponse:error
                                          responseData:operation.responseData];
                             }];
  

    [_operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        
         float  p =  (float) totalBytesWritten/totalBytesExpectedToWrite;
         NSLog(@"上传进度:%f",p);
//        request.success = YES;
//        request.isRetainBlock = YES;
//        [request excuteBlockWithObject:[NSNumber numberWithFloat:p]];
//        
    }];
    */
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",nil];
    [self addHeaderParams:manager];
    //    NSString *_token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    //    [manager.requestSerializer  setValue:_token forHTTPHeaderField:@"token"];
    [self addHeaderParams:manager];
    
    [manager POST:url parameters:url constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSArray *keys = self.requestParams.allKeys;
        NSArray *values = self.requestParams.allValues;
        
        for (NSInteger i = 0; i < keys.count; i++) {
            NSString *key  = keys[i];
            NSString *value = [NSString stringWithFormat:@"%@",values[i]];
            if ([key isEqual:@"file"]) {
                NSString *path = [self.requestParams objectForKey:@"file"];
                NSError *error;
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file"  error:&error];
            }else {
                NSData *jsonData = [value dataUsingEncoding:NSUTF8StringEncoding];
                [formData appendPartWithFormData:jsonData name:key];
            }
            
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
       
        NSLog(@"上传进度:%@",uploadProgress);

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DebugLog(@"上传文件成功:%@",responseObject);
        [self  handleResponse:responseObject
                 responseData:nil] ;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self  handleResponse:error
                 responseData:nil];
    }];
    
}

-(void)addHeaderParams:(AFHTTPSessionManager *)manager{
    
    NSDictionary *requestHeaders = [AIRequest requestHeaders];
    
    [requestHeaders enumerateKeysAndObjectsUsingBlock:^(NSString*  _Nonnull key, NSString*  _Nonnull obj, BOOL * _Nonnull stop) {
        [manager.requestSerializer setValue:obj forHTTPHeaderField:key];

    }];
    
 
}
@end


